package com.bbs.pojo;

import com.bbs.utils.Constants;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T>{
    private String code;
    private String message;
    private T data;

    public static <T> Result<T> succeed(T data){
        return new Result<T>(Constants.SUCCESS_CODE, Constants.SUCCESS_MESSAGE, data);
    }

    public static Result<Object> succeed(){
        return new Result<>(Constants.SUCCESS_CODE, Constants.SUCCESS_MESSAGE, null);
    }

    public static Result<Object> fail(){
        return new Result<>(Constants.FAILURE_CODE, Constants.FAILURE_MESSAGE, null);
    }

    public static Result<Object> build(boolean isSuccessful){
        if(isSuccessful){
            return succeed();
        }else{
            return fail();
        }
    }

    /**
     * 创建携带数据的Result对象。若data为null，返回错误ENTITY_NOT_EXIST
     */
    public static <T> Result<T> withData(T data){
        if(data != null){
            return succeed(data);
        }else{
            Result<T> result = new Result<>();
            result.code = Constants.ENTITY_NOT_EXIST_CODE;
            result.message = Constants.ENTITY_NOT_EXIST_MESSAGE;
            return result;
        }
    }
}
